package com.shop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.constant.Constants;
import com.shop.exception.DAOException;
import com.shop.factory.ObjectFactory;
import com.shop.util.GetMap;
import com.shop.util.MD5Util;
import com.shop.util.PrintJson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: ${file_name}</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2020</p>
 * <p>Company: www.baidudu.com</p>
 *
 * @author andy
 * @version 1.0
 * @date ${date}
 */
@WebServlet("/user/*")
public class UserController extends HttpServlet{

    private IUserService service =
            (IUserService) ObjectFactory.getInstance(Constants.USER_SERVICE_KEY);

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        if("/shop/user/login".equals(uri)) {
            login(req,resp);
        }
    }

    private void login(HttpServletRequest req, HttpServletResponse resp)
    throws  ServletException,IOException{
        //解析
        JSONObject json = PrintJson.paraseJson(req);

        String username = json.getString("username");
        String password = json.getString("password");
        //md5加密
        password = MD5Util.getMD5(password);

        try{
            service.login(username, password);
            User user = service.searchByName(username);

            Map<String, Object> map = GetMap.getMap(200, "登录成功");
            map.put("data",user);

            PrintJson.printJsonObj(resp,map);

        }catch(DAOException e){
            System.out.println(e.getMessage());
        } catch (UserIsNotExistException e) {
            System.out.println(e.getMessage());
        } catch (UserNameOrPasswordException e) {
            System.out.println(e.getMessage());
        }
    }

}
